<template>
  <div class="notice-management">
    <!-- 搜索区域 -->
    <div class="search-box">
      <el-input v-model="searchParams.id" placeholder="ID" style="width:200px" />
      <el-input v-model="searchParams.name" placeholder="公告名称" style="width:200px" />
      <el-button type="primary" @click="fetchData">搜索</el-button>
      <el-button type="success" @click="openAddDialog">新增公告</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border>
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column label="图片" width="120">
        <template #default="{row}">
          <el-image
              v-if="row.noticeimg"
              :src="row.noticeimg"
              style="width:80px;height:60px"
              :preview-src-list="[row.noticeimg]"
              preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column prop="noticename" label="公告名称" />
      <el-table-column prop="noticecontent" label="公告内容" show-overflow-tooltip />
      <el-table-column prop="noticetime" label="发布日期" :formatter="formatDate" width="150" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{row}">
          <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteNotice(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        @current-change="fetchData"
        @size-change="fetchData"
    />

    <!-- 新增对话框 -->
    <el-dialog v-model="addDialog.visible" title="新增公告" width="600px">
      <el-form :model="addForm" label-width="100px" ref="addFormRef">
        <el-form-item label="ID" prop="noticename" required>
          <el-input v-model="addForm.id" />
        </el-form-item>
        <el-form-item label="公告名称" prop="noticename" required>
          <el-input v-model="addForm.noticename" />
        </el-form-item>
        <el-form-item label="公告内容" prop="noticecontent" required>
          <el-input v-model="addForm.noticecontent" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="发布日期" prop="noticetime" required>
          <el-date-picker
              v-model="addForm.noticetime"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="公告图片">
          <el-upload
              action="#"
              :auto-upload="false"
              :on-change="handleAddImageChange"
              :show-file-list="false"
          >
            <el-button type="primary">选择图片</el-button>
            <span v-if="addForm.noticeimg" style="margin-left:10px">{{ addForm.noticeimg.name }}</span>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitAddForm">提交</el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialog.visible" title="编辑公告" width="600px">
      <el-form :model="editForm" label-width="100px" ref="editFormRef">
        <el-form-item label="ID" prop="id">
          <el-input v-model="editForm.id" disabled />
        </el-form-item>
        <el-form-item label="公告名称" prop="noticename" required>
          <el-input v-model="editForm.noticename" />
        </el-form-item>
        <el-form-item label="公告内容" prop="noticecontent" required>
          <el-input v-model="editForm.noticecontent" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="发布日期" prop="noticetime" required>
          <el-date-picker
              v-model="editForm.noticetime"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="公告图片">
          <el-upload
              action="#"
              :auto-upload="false"
              :on-change="handleEditImageChange"
              :show-file-list="false"
          >
            <el-button type="primary">更换图片</el-button>
            <div v-if="editForm.noticeimgUrl" style="margin-top:10px">
              <el-image :src="editForm.noticeimgUrl" style="width:100px;height:80px" />
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 数据状态
const searchParams = reactive({ id: '', name: '' })
const pagination = reactive({ page: 1, size: 10, total: 0 })
const tableData = ref([])

// 新增相关
const addDialog = reactive({ visible: false })
const addForm = reactive({
  id: '',
  noticename: '',
  noticecontent: '',
  noticetime: '',
  noticeimg: null
})
const addFormRef = ref()

// 编辑相关
const editDialog = reactive({ visible: false })
const editForm = reactive({
  id: '',
  noticename: '',
  noticecontent: '',
  noticetime: '',
  noticeimg: null,
  noticeimgUrl: ''
})
const editFormRef = ref()

// 初始化加载数据
onMounted(fetchData)

// 获取数据
async function fetchData() {
  try {
    const params = {
      pageNum: pagination.page,
      pageSize: pagination.size,
      ...searchParams
    }
    const res = await axios.get('/api/notice/getAllData', { params })
    tableData.value = res.data.data.list
    pagination.total = res.data.data.total
  } catch (error) {
    ElMessage.error('获取数据失败: ' + error.message)
  }
}

// 打开新增对话框
function openAddDialog() {
  addDialog.visible = true
  Object.assign(addForm, {
    noticename: '',
    noticecontent: '',
    noticetime: '',
    noticeimg: null
  })
}

// 打开编辑对话框
function openEditDialog(row) {
  editDialog.visible = true
  Object.assign(editForm, {
    id: row.id,
    noticename: row.noticename,
    noticecontent: row.noticecontent,
    noticetime: row.noticetime,
    noticeimg: null,
    noticeimgUrl: row.noticeimg
  })
}

// 处理新增图片上传
function handleAddImageChange(file) {
  addForm.noticeimg = file.raw
}

// 处理编辑图片上传
function handleEditImageChange(file) {
  editForm.noticeimg = file.raw
}

// 提交新增表单
async function submitAddForm() {
  try {
    const formData = new FormData()
    formData.append('id', addForm.id)
    formData.append('noticename', addForm.noticename)
    formData.append('noticecontent', addForm.noticecontent)
    formData.append('noticetime', addForm.noticetime)
    if (addForm.noticeimg) {
      formData.append('noticeimg', addForm.noticeimg)
    }

    await axios.post('/api/notice', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })

    ElMessage.success('新增成功')
    addDialog.visible = false
     fetchData()
  } catch (error) {
    ElMessage.error('新增失败: ' + error.message)
  }
}

// 提交编辑表单
async function submitEditForm() {
  try {
    const formData = new FormData()
    formData.append('noticename', editForm.noticename)
    formData.append('noticecontent', editForm.noticecontent)
    formData.append('noticetime', editForm.noticetime)
    if (editForm.noticeimg) {
      formData.append('noticeimg', editForm.noticeimg)
    }

    await axios.put(`/api/notice/${editForm.id}`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })

    ElMessage.success('更新成功')
    editDialog.visible = false
    fetchData()
  } catch (error) {
    ElMessage.error('更新失败: ' + error.message)
  }
}

// 删除公告
async function deleteNotice(id) {
  try {
    await ElMessageBox.confirm('确定删除该公告吗?', '提示', { type: 'warning' })
    await axios.delete(`/api/notice/${id}`)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 日期格式化
function formatDate(row, column, cellValue) {
  return new Date(cellValue).toLocaleDateString()
}
</script>

<style scoped>
.notice-management {
  padding: 20px;
}
.search-box {
  margin-bottom: 20px;
}
.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
